from django.shortcuts import render, HttpResponse
from myapp.utils.Bootstrap import BootstrapModelForm
from myapp import models
from django.views.decorators.csrf import csrf_exempt  # 免除csrf验证
import json
from django import forms


class TaskModelForm(BootstrapModelForm):
    class Meta:
        model = models.Task
        widgets = {
            'detail': forms.TextInput
        }
        fields = '__all__'


def task_list(request):
    form = TaskModelForm
    return render(request, 'task_list.html', {'form': form})


@csrf_exempt  # #免除csrf验证
def task_ajax(request):
    if request.method == 'GET':
        print(request.GET)
        return HttpResponse("ajax GET方式请求成功")
    data = {
        'name': '王萌',
        "age": 12
    }
    print(request.POST)
    return HttpResponse(json.dumps(data))


@csrf_exempt
def task_add(request):
    form = TaskModelForm(data=request.POST)
    print(request.POST)
    if form.is_valid():
        form.save()
        data_dict = {'status': "True",}
        return HttpResponse(json.dumps(data_dict))
    data_dict = {'status': "False",'error':form.errors}
    return HttpResponse(json.dumps(data_dict,ensure_ascii=False))
